# import socket
#
# # 创建服务器套接字实例
# server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#
# # 绑定IP和端口
# SERVER_INFO = ("192.168.11.151", 60000)
# server_socket.bind(SERVER_INFO)
#
# # 开始侦听
# server_socket.listen()
#
# # 接受客户端的连接
# client_socket, client_addr = server_socket.accept()
# print(client_addr, "连接上了")
#
# # 向客户端发送消息
# send_msg = input("请输入发送信息")
# send_bytes = send_msg.encode("gbk")
# client_socket.send(send_bytes)
#
# # 接收客户端信息
# recv_bytes = client_socket.recv(1024)
# recv_msg = recv_bytes.decode("gbk")
# print(f"收到消息", recv_msg)
#
# # 关闭客户端 关闭服务器
# client_socket.close()
# server_socket.close()







import socket
import threading


def t_recv_main(client_socket, client_addr):
    while True:
        recv_bytes = client_socket.recv(1024)
        if len(recv_bytes) == 0:
            for client in client_l:
                if client[0] == client_addr[1]:
                    client_l.remove(client)
                    print(f"客户端{client_addr} 断开了 当前共有客户端{len(client_l)}个")
                    break
            break
        recv_msg = recv_bytes.decode("gbk")
        print(f"接收消息 {client_addr} {recv_msg}")


def t_accept_main(server_socket):
    while True:
        client_socket, client_addr = server_socket.accept()
        client_l.append([client_addr[1], client_socket])
        print(f"{client_addr}连接了 当前共{len(client_l)}个客户端")

        t_recv = threading.Thread(target=t_recv_main, args=(client_socket, client_addr))
        t_recv.start()


client_l = []


def main():
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    SERYER_ADDR = ("192.168.11.151", 60000)
    server_socket.bind(SERYER_ADDR)
    server_socket.listen()
    print(f"服务器启动了")

    t_accept = threading.Thread(target=t_accept_main, args=(server_socket, ))
    t_accept.start()

    while True:
        port = input("输入发送客户端的端口")
        port = int(port)
        for client in client_l:
            if client[0] == port:
                send_msg = input("输入发送信息")
                send_bytes = send_msg.encode("gbk")
                client[1].send(send_bytes)
                break
        else:
            print(f"没有找到对应的客户端")


if __name__ == '__main__':
    main()

